package com.qianye.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.qianye.realm.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean() {
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(getDefaultWebSecurityManager());
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("/", "anon");
        map.put("/css/**", "anon");
        map.put("/fonts/**", "anon");
        map.put("/images/**", "anon");
        map.put("/js/**", "anon");
        map.put("/lib/**", "anon");
        map.put("/login", "anon");
        map.put("/logout","logout");
        map.put("/toregister","anon");
        map.put("/customer/register","anon");
        map.put("/customer/login","anon");
        map.put("/**", "authc");
        filterFactoryBean.setFilterChainDefinitionMap(map);
        //设置没有认证时跳转的路径
        filterFactoryBean.setLoginUrl("/");
        return filterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(getMyRealm());
        return securityManager;
    }

    @Bean
    public MyRealm getMyRealm() {
        MyRealm realm = new MyRealm();
        realm.setCredentialsMatcher(getHashedCredentialsMatcher());
        return realm;
    }

    @Bean
    public HashedCredentialsMatcher getHashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5");
        return matcher;
    }

    @Bean
    public ShiroDialect getShiroDialect() {
        return new ShiroDialect();
    }
}
